package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.enums.StatusGradeEnum;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 班级 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-07-26
 */
@Service
public class GradeServiceImpl extends ServiceImpl<GradeMapper, Grade> implements IGradeService {
    @Autowired
    IdWorker idWorker;

    @Resource
    @Lazy
    CourseMapper courseMapper;

    @Resource
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    CompanyMapper companyMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    ITypeValueDataService iTypeValueDataService;

    @Autowired
    @Lazy
    IRenewDataService iRenewDataService;

    @Autowired
    @Lazy
    ISubjectsService iSubjectsService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Transactional
    public boolean saveTo(Grade grade){
        grade.setId(idWorker.nextId());

        List<TypeValueData> typeValueDataList = new ArrayList<>();

        Iterator<TypeValueData> iterator = grade.getTeacherList().iterator();
        Integer i = 0;
        Integer j = 0;
        while (iterator.hasNext()){
            TypeValueData typeValueData = iterator.next();
            if(typeValueData.getValueId()!= null && typeValueData.getTypeId()!=null){
                typeValueData.setForId(grade.getId());
                typeValueData.setType(21);
                typeValueDataList.add(typeValueData);
                /**
                 * 把第一位的老师和助教设置到班级上
                 */
                if(typeValueData.getTypeId() == 1){
                    if(i==0){
                        grade.setTeacherId(typeValueData.getValueId());
                        i++;
                    }
                }else {
                    if(j==0){
                        grade.setHelpTeacherId(typeValueData.getValueId());
                        j++;
                    }
                }
            }
        }
        if(typeValueDataList.size()>0){
            iTypeValueDataService.saveBatch(typeValueDataList);
        }
        Course course = courseMapper.findOne(grade.getCourseId());
        grade.setYearClassId(course.getYearClassId());




        this.save(grade);
        return true;
    }

    @Transactional
    public boolean updateTo(Grade grade){

        //System.out.println();
        //System.out.print("updateTo");
        List<TypeValueData> typeValueDataList = new ArrayList<>();
        List<TypeValueData> upTypeValueDataList = new ArrayList<>();
        Set<Long> atTypeValueData = new HashSet<>();

        Integer i = 0;
        Integer j = 0;
        Iterator<TypeValueData> iterator = grade.getTeacherList().iterator();
        while (iterator.hasNext()){
            TypeValueData typeValueData = iterator.next();

            if(typeValueData.getValueId()!= null && typeValueData.getTypeId()!=null) {
                if(typeValueData.getId() == null){
                    typeValueData.setForId(grade.getId());
                    typeValueData.setType(21);
                    typeValueDataList.add(typeValueData);
                }else{
                    typeValueData.setForId(grade.getId());
                    typeValueData.setType(21);
                    upTypeValueDataList.add(typeValueData);
                    atTypeValueData.add(typeValueData.getId());
                }

                /**
                 * 把第一位的老师和助教设置到班级上
                 */
                if(typeValueData.getTypeId() == 1){
                    if(i==0){
                        grade.setTeacherId(typeValueData.getValueId());
                        i++;
                    }
                }else {
                    if(j==0){
                        grade.setHelpTeacherId(typeValueData.getValueId());
                        j++;
                    }
                }
            }
        }

        //删除
        if(atTypeValueData.size() > 0){
            //System.out.print("grade:"+grade.getId());
            //System.out.print(atTypeValueData);
            QueryWrapper<TypeValueData> queryWrapper =  new QueryWrapper<>();
            queryWrapper.notIn("id",atTypeValueData);
            queryWrapper.eq("for_id",grade.getId());
            iTypeValueDataService.remove(queryWrapper);
        }else {
            QueryWrapper<TypeValueData> queryWrapper =  new QueryWrapper<>();
            queryWrapper.eq("for_id",grade.getId());
            iTypeValueDataService.remove(queryWrapper);
        }
        //新增
        if(typeValueDataList.size()>0){
            iTypeValueDataService.saveBatch(typeValueDataList);
        }
        //修改
        if(upTypeValueDataList.size()>0){
            iTypeValueDataService.updateBatchById(upTypeValueDataList,upTypeValueDataList.size());
        }

        //修改主体
        this.updateById(grade);

        Course course = iCourseService.getById(grade.getCourseId());

        //更新排课信息里的课程科目，以后调整到异步修改
        UpdateWrapper<CourseSchedulingDetail> courseSchedulingDetailUpdateWrapper = new UpdateWrapper<>();
        Subjects subjects = iSubjectsService.getById(course.getSubjectsId());
        courseSchedulingDetailUpdateWrapper.eq("grade_id",grade.getId());
        courseSchedulingDetailUpdateWrapper.set("course_id",course.getId());
        courseSchedulingDetailUpdateWrapper.set("course_name",course.getName());
        courseSchedulingDetailUpdateWrapper.set("subjects_id",course.getSubjectsId());
        courseSchedulingDetailUpdateWrapper.set("subjects_name",subjects.getName());

        iCourseSchedulingDetailService.update(null,courseSchedulingDetailUpdateWrapper);



        return true;
    }

    public IPage<Grade> checkGrade(IPage<?> page, Wrapper wrapper,Long schoolId){
        IPage<Grade> iPage = gradeMapper.checkGrade(page,wrapper);
        List<Grade> gradeList = iPage.getRecords();
        for (Grade grade:gradeList){
            Course course = grade.getCourseObj();
            List<CoursePricing> coursePricingList = courseMapper.coursePricingForSchoolIdList(course.getId(),schoolId);
            course.setCoursePricingList(coursePricingList);

            QueryWrapper<Grade> gradeQueryWrapper = new QueryWrapper<>();
            gradeQueryWrapper.eq("deleted",0);
            gradeQueryWrapper.eq("school_id",schoolId);
            gradeQueryWrapper.eq("course_id",course.getId());
            List<Grade> gradeList1 = gradeMapper.selectList(gradeQueryWrapper);
            course.setGradeList(gradeList1);
        }
        return iPage;
    }
    /*public List<Map<String,Object>> checkGrade(Map<String,Object> map){
        List<Map<String,Object>> mapList = gradeMapper.checkGrade(map);
        Iterator iterator = mapList.iterator();
        while (iterator.hasNext()){
            Map<String,Object> map1 = (Map<String, Object>) iterator.next();
            List<Map<String,Object>> mapList2 = courseMapper.coursePricingForSchoolIdList(Long.valueOf(String.valueOf(map1.get("course_id"))),Long.valueOf(String.valueOf(map.get("school_id"))));
            map1.put("coursePricingList",mapList2);
        }
          return mapList;
    }*/



    public IPage<Grade> findAll(IPage<?> page, Wrapper wrapper){
        IPage<Grade> gradeIPage = gradeMapper.findAll(page,wrapper);
        for (Grade grade:gradeIPage.getRecords()){
                Integer count = studentGradeMapper.studentCount(grade.getSchoolObj().getId(),grade.getId());
                grade.setCount(count);
        }

        return gradeIPage;
    }

    public Grade getOneForId(Long id){
        Grade grade = gradeMapper.getOneForId(id);
        Integer count = studentGradeMapper.studentCount(grade.getSchoolObj().getId(),grade.getId());
        grade.setStudentCount(count);
        return grade;
    }

    public List<Grade> getGradeForCheck(Long schoolId,Long courseId){
        //获取班级开了该课程的班级
        QueryWrapper<Grade> gradeQueryWrapper = new QueryWrapper<>();
        gradeQueryWrapper.eq("deleted",0);
        gradeQueryWrapper.eq("school_id",schoolId);
        gradeQueryWrapper.eq("course_id",courseId);
        List<Grade> gradeList = gradeMapper.selectList(gradeQueryWrapper);
        return gradeList;
    }

    @Transactional
    public Boolean addStudent(String gradeId,String[] studentIdList){

        Grade grade = gradeMapper.selectById(Long.parseLong(gradeId));
        Course course = courseMapper.selectById(grade.getCourseId());
        //年份与月份
        Integer yearAndQuarter = Integer.parseInt(grade.getYearPart()+""+course.getQuarterNum());
        List<StudentGrade> studentGradeList = new ArrayList<>();
        for (String studentId:studentIdList){
            //剩余课时
            Integer courseHouse = orderDetailMapper.getResidueCourseCountForSubjects(grade.getSchoolId(),Long.parseLong(studentId),course.getSubjectsId(),yearAndQuarter,grade.getLessonType(),grade.getYearClassId().getKey());
            OrderDetail orderDetail = orderDetailMapper.getLastOneForSubjectId(grade.getSchoolId(),Long.parseLong(studentId),course.getSubjectsId());

            Integer isAtGrade = studentGradeMapper.studentIsAtGrade(Long.parseLong(studentId),grade.getId());
            //System.out.print("isAtGrade:"+isAtGrade);
            if(isAtGrade == 0){
                StudentGrade studentGrade =  new StudentGrade();
                studentGrade.setSchoolId(grade.getSchoolId());
                studentGrade.setGradeId(grade.getId());
                studentGrade.setCourseId(grade.getCourseId());
                studentGrade.setSubjectsId(course.getSubjectsId());
                studentGrade.setYearPart(grade.getYearPart());
                studentGrade.setQuarterNum(course.getQuarterNum());
                studentGrade.setSurplusCourseNum(courseHouse);
                studentGrade.setStudentId(Long.parseLong(studentId));
                if(orderDetail != null){
                    studentGrade.setOrderDetailId(orderDetail.getId());
                }
                //System.out.print("添加成功:"+isAtGrade);
                studentGradeMapper.insert(studentGrade);
                iRenewDataService.updateTeacher(grade.getSchoolId(),Long.parseLong(studentId),course,grade);
            }




        }
        return true;
    }

    public Boolean endOfShift(Long gradeId){
            Grade grade = gradeMapper.selectById(gradeId);
            boolean rs = false;
            if(grade!=null){
                if(grade.getStatus().getKey() == 1){
                    grade.setStatus(StatusGradeEnum.DISABLE);
                    gradeMapper.updateById(grade);

                    //设置班里的学生为结课
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("grade_id",gradeId);
                    studentGradeQueryWrapper.eq("deleted",0);
                    studentGradeQueryWrapper.eq("status",1);
                    studentGradeQueryWrapper.eq("reading_status",1);
                    List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);

                    for (StudentGrade studentGrade:studentGradeList){
                        studentGrade.setReadingStatus(ReadingStatusEnum.FINISH);
                        studentGradeMapper.updateById(studentGrade);
                    }

                    /*
                    List<Integer> readingStatusList = new ArrayList<>();
                    readingStatusList.add(1);
                    readingStatusList.add(4);
                    UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                    studentGradeUpdateWrapper.eq("grade_id",gradeId);
                    studentGradeUpdateWrapper.eq("status",1);
                    studentGradeUpdateWrapper.eq("deleted",0);
                    studentGradeUpdateWrapper.in("reading_status",readingStatusList);
                    studentGradeUpdateWrapper.set("reading_status",5);
                    studentGradeMapper.update(null,studentGradeUpdateWrapper);*/
                    rs = true;
                }
            }
            return rs;
    }
}
